<script setup>
import { getCurrentInstance, nextTick, onMounted,ref } from "vue";
import {BaiduMap} from "vue-baidu-map-3x";

const { proxy } = getCurrentInstance();
const props = defineProps({
  lng: {
    type: Number,
    default: 113.31071
  },
  lat: {
    type: Number,
    default: 23.14828
  },
  address: {
    type: String,
    default:null
  }
});

const iconUrl ='icon/map_marker_check.png'
let map=null
const point = ref({})
const changeAddressMap = (v)=>{

  let gcx = new BMap.Geocoder();
    gcx.getPoint(v, function(e){
      if(e){
        point.value = new BMap.Point(e.lng, e.lat)
        let myMarker = new BMap.Marker(
            new BMap.Point(point.value.lng, point.value.lat)
        );
        map.addOverlay(myMarker)
      }
    }, '烟台市')
}
defineExpose({
  changeAddressMap
})
onMounted(() => {
  nextTick(() => {
    init();
  });
});
const params = ref({})
const init = async () => {
  const BMap = window.BMap;
  //显示级别，如省市区街，0-20
  let showLevel = 16;
  map = new BMap("baidu-map")
  //地图中心点，默认广州市
  point.value = new BMap.Point(props.lng, props.lat);
  // if(props.address){
  //   let gcx = new BMap.Geocoder();
  //   showLevel = 17;
  //   gcx.getPoint(props.address, function(e){
  //     if(e){
  //       point = e
  //       map.addOverlay(new BMap.Marker(point))
  //     }
  //   }, '烟台市')
  // }
  if(props.lng && props.lat){
    point.value = new BMap.Point(props.lng, props.lat);
    showLevel = 17;
    //设置初始坐标图标位置
    let myMarker = new BMap.Marker(
        new BMap.Point(props.lng, props.lat)
    );
    map.addOverlay(myMarker);
  }else if(props.address){
      let gcx = new BMap.Geocoder();
      showLevel = 17;
      gcx.getPoint(props.address, function(e){
        if(e){
          point.value = e
          let myMarker = new BMap.Marker(
              new BMap.Point(point.value.lng, point.value.lat)
          );
          map.addOverlay(myMarker)
        }
      }, '烟台市')
  }



  //设置中心坐标，显示级别
  map.centerAndZoom(point.value, showLevel);
  //获取当前定位
  map.addControl(new BMap.GeolocationControl());
  //开启鼠标滚轮缩放
  map.enableScrollWheelZoom(true);
  // 添加控件
  let opts = {type: "BMAP_NAVIGATION_CONTROL_SMALL"};
  map.addControl(new BMap.NavigationControl(opts));

  //创建点击事件
  map.addEventListener("click", function (e) {


    let gc = new BMap.Geocoder();
    gc.getLocation(e.point, function (rs) {

      params.value.address = rs.address;
      params.value.lng = e.point.lng;
      params.value.lat = e.point.lat;

    })
    //向父组件传值
    proxy.$emit("clickMap", params);

    //清除地图上所有覆盖物
    map.clearOverlays();
    //设置点击后图标显示
    let myMarker = new BMap.Marker(
        new BMap.Point(e.point.lng, e.point.lat)
    );
    map.addOverlay(myMarker);
  });

}
</script>

<template>
  <baidu-map id="baidu-map">

  </baidu-map>
</template>

<style scoped lang="scss">
#baidu-map {
  height: calc(80vh - 86px);
}
</style>